package dao;

import db.DBConnection;
import exceptions.DatabaseException;
import java.sql.*;
import java.util.List;

/**
 *
 * @author KAV
 */
abstract class AbstractDAO implements BaseDAO {

    protected DBConnection dbc;

    public AbstractDAO() {
        dbc = DBConnection.getInstance();
    }
    protected abstract PreparedStatement stringForInsert(Connection st, Object obj)throws DatabaseException;
    protected abstract PreparedStatement stringForDeleteById(Connection st, int id)throws DatabaseException;
    protected abstract PreparedStatement stringForUpdateById(Connection st, Object obj)throws DatabaseException;
    protected abstract List<Object> processForSelectAll(Connection st)throws DatabaseException;
    protected abstract Object processForSelectId(Connection st, int id)throws DatabaseException;

    private int bodyForChangeTables(PreparedStatement statement) throws DatabaseException{
        int result = 0;
        try {
            result = statement.executeUpdate();
            statement.getConnection().close();
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
        return result;
    }
    @Override
    public int insert(Object obj) throws DatabaseException {
        return bodyForChangeTables(stringForInsert(dbc.connect(), obj));
    }
    
    @Override
    public int deleteById(int id) throws DatabaseException {
        return bodyForChangeTables(stringForDeleteById(dbc.connect(),id));
    }
 
    @Override
    public int updateById(Object obj) throws DatabaseException {
        return bodyForChangeTables(stringForUpdateById(dbc.connect(), obj));
    }

    @Override
    public List<Object> selectAll() throws DatabaseException {
        List<Object> list = new java.util.LinkedList<Object>();
        try {
            Connection connection = dbc.connect();
            list=processForSelectAll(connection);
            connection.close();
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
        return list;
    }
 
    @Override
    public Object selectById(int id) throws DatabaseException {
        Object obj = new Object();
        try {
            Connection connection = dbc.connect();
            obj=processForSelectId(connection, id);
            connection.close();
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
        return obj;
    }

    @Override
    public List<Object> findByNameOrSurname(String query) throws DatabaseException {
        throw new UnsupportedOperationException();
    }

}
